package com.yinhai.message.implement.dwr.listener;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpSession;

import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;

/**
 * @author maxp
 * @Create 2017-01-04-15:55
 */
public class DWRScriptSessionListener implements ScriptSessionListener {

    public static final ConcurrentHashMap<String, ScriptSession> scriptSessionMap = new ConcurrentHashMap<>();

    @Override
    public void sessionCreated(ScriptSessionEvent ev) {
        WebContext webContext = WebContextFactory.get();
        HttpSession session = webContext.getSession();
        ScriptSession scriptSession = ev.getSession();
        String page = scriptSession.getPage();
//        String pageid = page.substring(page.lastIndexOf("/")+1,page.lastIndexOf("."));
        String pageid = page.replaceAll("/","");
        scriptSessionMap.put(session.getId()+pageid,scriptSession);
    }

    @Override
    public void sessionDestroyed(ScriptSessionEvent ev) {
        WebContext webContext = WebContextFactory.get();
        HttpSession session = webContext.getSession();
        ScriptSession scriptSession = ev.getSession();
        String page = scriptSession.getPage();
//        String pageid = page.substring(page.lastIndexOf("/")+1,page.lastIndexOf("."));
        String pageid = page.replaceAll("/","");
        scriptSessionMap.remove(session.getId()+pageid);
    }

    public static Collection<ScriptSession> getScriptSessions(){
        return scriptSessionMap.values();
    }
}
